<?php

namespace App\Miya\Middlewares;

use Closure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class UserView
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //本地测试,不记录uv
        if (request()->getClientIp() == '127.0.0.1') {
            return $next($request);
        }

        $data = [
            'time' => now()->format('Y-m-d H:i:00'),
            'ip' => request()->getClientIp(),
        ];
        $key = sprintf('uv_%s', md5(json_encode($data)));
        if (!Cache::has($key)) {
            Cache::add($key, 1, config('miya.view_frequency'));

            $data['referer_url'] = request()->server('HTTP_REFERER');
            $data['url'] = request()->url();

            DB::table('user_views')->insertOrIgnore($data);
        }
        return $next($request);
    }
}
